import fs from "fs";
import path from "path";
import pdb from "src/db/project";
import sdb from "src/db/snapshot";
import field from "src/config/field";
import res from "src/utils/response";

export async function remove(ctx: Context, params: any) {
  const srow: any = await sdb.queryOne(params, "id");
  if (srow && srow.del_flag === 1) {
    const { project_id, git_commit_id } = srow;
    const prow: any = await pdb.queryOne({ id: project_id }, "id");
    const hashPath = path.join(prow.deploy_path, git_commit_id);
    const deployPath = path.join(prow.deploy_path, prow.deploy_folder_name);
    fs.rmSync(hashPath, { recursive: true, force: true });
    if (srow.snapshot_status === 2) {
      fs.rmSync(deployPath, { recursive: true, force: true });
    }
    await sdb.remove(params.id);
    ctx.body = res.ok();
  } else {
    ctx.body = res.fail("该项目不存在");
  }
}

export async function query(ctx: Context, params: any) {
  const rows = await sdb.query(field.snapshot, params);
  ctx.body = res.ok(rows);
}
